package com.zch.socket.aio.client2;

import com.zch.socket.common.ByteUtils;
import com.zch.socket.common.model.RequestModel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class Client implements Runnable  {
    private AsynchronousSocketChannel clientChannel;
    private String remoteAddress;//需要连接的远端地址
    private int port;//待连接的远端端口

    /**
     * 构造方法
     * @param remoteAddress
     * @param port
     */
    public Client(String remoteAddress, int port) {
        this.remoteAddress = remoteAddress;
        this.port = port;
        try {
            //创建异步的客户端通道
            clientChannel = AsynchronousSocketChannel.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        System.out.println("客户端发起连接");
        //创建异步的客户端通道
        try{
            ClientConnectHandler clientConnectHandler=new ClientConnectHandler();
            //发起连接
            clientChannel.connect(new InetSocketAddress(remoteAddress, port), clientConnectHandler, clientConnectHandler);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public boolean sendMsg(String s){
        RequestModel requestModel=new RequestModel();
        Object[] srt={s};
        requestModel.setParams(srt);
        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
        byteBuffer= ByteUtils.ObjectToByteBuffer(byteBuffer,requestModel);
        //异步写
        clientChannel.write(byteBuffer,byteBuffer,new ClientWriterHandler(clientChannel));
        return true;

    }
}
